package com.gitee.feizns.itrip.personal.trade.controller;

import com.gitee.feizns.itrip.personal.beans.dto.Dto;
import com.gitee.feizns.itrip.personal.beans.pojo.HotelOrder;
import com.gitee.feizns.itrip.personal.utils.service.WeChatPayService;
import com.gitee.feizns.itrip.personal.trade.entity.vo.ForViewCreateQcCode;
import com.gitee.feizns.itrip.personal.trade.service.TradeHotelOrderService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;

import static com.gitee.feizns.itrip.personal.utils.service.WeChatPayService.OK;
import static com.gitee.feizns.itrip.personal.utils.service.WeChatPayService.SUCCESS;

/**
 * @author feizns
 * @since 2019/1/15 0015
 */
@RestController
@RequestMapping("/api/wxpay")
public class WeChatPaymentController {

    @Autowired
    private TradeHotelOrderService tradeHotelOrderService;

    @Autowired
    private WeChatPayService weChatPayService;

    /**
     * 测试金额
     */
    public static final String TOTAL_FEE_FOR_TEST = "1";

    @GetMapping("/createqccode/{orderNo}")
    public Dto<ForViewCreateQcCode> createQcCode(@PathVariable String orderNo) {
        ForViewCreateQcCode qcCode = tradeHotelOrderService.getOrderForViewCreateQcCode(orderNo);
        if ( qcCode != null )
            qcCode.setCodeUrl(weChatPayService.getCodeUrl(orderNo, TOTAL_FEE_FOR_TEST, qcCode.getHotelName()));
        return Dto.getSuccessDto(null, qcCode);
    }

    @GetMapping("/queryorderstatus/{orderNo}")
    public Dto<HotelOrder> queryOrderStatus(@PathVariable String orderNo) {
        return Dto.getSuccessDto(null, tradeHotelOrderService.get(orderNo));
    }

    @PostMapping(value = "/notifyUrl", produces = "text/xml;charset=utf-8")
    public void notifyUrl(InputStream is, HttpServletResponse resp) throws Exception {
        String xml = IOUtils.toString(is, WeChatPayService.DEFAULT_CHARSET);
        WeChatPayService.WeChatReturn weChatReturn = WeChatPayService.WeChatReturn.parse(xml);
        if ( SUCCESS.equals(weChatReturn.getReturnCode()) && SUCCESS.equals(weChatReturn.getResultCode()) ) {
            tradeHotelOrderService.confirmOrder(weChatReturn.getOutTradeNo(), weChatReturn.getTransactionId(), TradeHotelOrderService.WE_CHAT_PAY_TYPE);
        }

        PrintWriter out = resp.getWriter();
        out.println(new WeChatPayService.WeChatReturn().setReturnCode(SUCCESS).setReturnMsg(OK).toXml());
        out.flush();
    }

}
